from itsdangerous import  TimedJSONWebSignatureSerializer as TJWSSerializer, BadData
from django.conf import settings


def generate_save_user_token(openid):
    """
    将明文openid序列化成密文openid
    :param openid:
    :return:
    """
    #创建序列化对象
    s = TJWSSerializer(settings.SECRET_KEY,600)
    #构造原始数据
    data = {'openid':openid}
    #序列化字典:dumps返回bytes类型的数据
    token = s.dumps(data).decode()
    return token


def check_save_user_token(access_token):
    """
    讲密文转化成明文
    :param token: token
    :return: openid or None
    """
    serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=600)
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')